package com.ittony.health.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicSessionCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Map;

public class AccessCOSUtil {
    public static void uploadImage(String fileName, byte[] imageBytes) {
        Map<String, String> keyGenerated = KeyGeneratedUtil.keyGenerated();
        // 用户基本信息
        String tmpSecretId = keyGenerated.get("tmpSecretId");   // 替换为 STS 接口返回给您的临时 SecretId
        String tmpSecretKey = keyGenerated.get("tmpSecretKey");  // 替换为 STS 接口返回给您的临时 SecretKey
        String sessionToken = keyGenerated.get("sessionToken");  // 替换为 STS 接口返回给您的临时 Token

        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);
        // 2 设置 bucket 区域,详情请参见 COS 地域 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing"));
        // 3 生成 cos 客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket 名需包含 appid
        String bucketName = "health-project-1255550961";

        String key = "health/images/"+ fileName;
        // 上传 object, 建议 20M 以下的文件使用该接口
        // File localFile = new File("src/test/resources/text.txt");
        InputStream stream = new ByteArrayInputStream(imageBytes);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(imageBytes.length);
        metadata.setContentType("image/jpeg");
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, stream, metadata);

        // 设置 x-cos-security-token header 字段
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setSecurityToken(sessionToken);
        putObjectRequest.setMetadata(objectMetadata);

        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // 成功：putobjectResult 会返回文件的 etag
            String etag = putObjectResult.getETag();
        } catch (CosServiceException e) {
            //失败，抛出 CosServiceException
            e.printStackTrace();
        } catch (CosClientException e) {
            //失败，抛出 CosClientException
            e.printStackTrace();
        }
    }
}
